<?php

namespace App\Http\Controllers\Admin;

use App\Http\Resources\ApplyCollection;
use App\Models\Apply;
use App\Models\ApplyHasPlayer;
use App\Models\Drawlot;
use App\Models\PlayerUser;
//use App\Validates\RoleValidate;
use Illuminate\Http\Request;
use Log;

class ApplysController extends AdminController
{
    public function __construct()
    {
        parent::__construct();
        $this->middleware('auth:api');
    }

    public function ApplyList(Request $request, Apply $apply)
    {
        $search_data = json_decode($request->get('search_data'), true);
        if ($search_data['season']) {
            $apply = $apply->columnLike('season', $search_data['season']);
        }
        return new ApplyCollection($apply->get());
    }

    public function addEditApply(Request $request, Apply $apply/*, RoleValidate $validate*/)
    {
        $update_data = $request->only('id', 'apply_type', 'league_id', 'cup_id', 'name', 'season', 'time', 'max', 'end_time', 'play_time', 'play_place', 'play_cost', 'play_detail');
        $apply_id = $request->post('id', 0);
        if ($apply_id > 0) {
            $apply = $apply->findOrFail($apply_id);
            //$rest_validate = $validate->updateValidate($update_data, $apply_id);
        } else {
            //$rest_validate = $validate->storeValidate($update_data);
        }

        //if ($rest_validate['status'] === false) return $this->failed($rest_validate['message']);

        //$res = $apply->saveData($update_data);
        $res = $apply->fill($update_data)->save();

        if ($res) return $this->message('操作成功');
        return $this->failed('内部错误');
    }

    public function destroy(Apply $apply/*, RoleValidate $roleValidate*/)
    {
        if (!$apply) return $this->failed('找不到角色', 404);
        /*$rest_destroy_validate = $roleValidate->destroyValidate($role);
        if ($rest_destroy_validate['status'] === true) {*/
            $rest_destroy = $apply->delete();
            if ($rest_destroy['status'] === true) return $this->message($rest_destroy['message']);
            return $this->failed($rest_destroy['message'], 500);
        /*} else {
            return $this->failed($rest_destroy_validate['message']);
        }*/
    }

    //根据id获得单挑报名信息
    public function info(Apply $apply/*, RoleValidate $roleValidate*/)
    {
        Log::info('info--------------------');
        if (!$apply) return $this->failed('找不到比赛', 404);
        return $this->success(['apply' => $apply]);
    }
    
    //获取可以参加该报名的所有user
    public function applyUserList(Apply $apply/*, RoleValidate $roleValidate*/)
    {
        if (!$apply) return $this->failed('找不到比赛', 404);
        Log::info($apply->apply_type);
        Log::info($apply->league_id);
        Log::info($apply->cup_id);
        if($apply->apply_type=='L'){
            $users = PlayerUser::where('league_id', $apply->league_id)->get();
        }else if($apply->apply_type=='C'){
            $users = PlayerUser::where('cup_id', $apply->cup_id)->get();
        }
        return $this->success(['users' => $users]);
    }

    //分档位得到该报名下所有档位报名的队员
    public function playerbyplayer(Apply $apply/*, RoleValidate $roleValidate*/)
    {
        if (!$apply) return $this->failed('找不到比赛', 404);
        $level = 0;
        $applyHasPlayer = [];
        $player = [];
        $is_over = false;
        for($level=0;$level<10;$level++){
            $player = ApplyHasPlayer::with('user')
                                        ->where('apply_id', '=', $apply->id)
                                        ->where('user_level', '=', $level)
                                        ->get();
            if(count($player)>0){
                //array_push($applyHasPlayer, $player);
                $applyHasPlayer[$level] = $player;
            }
            $player = [];
        }
        log::info($applyHasPlayer);
        return $this->success(['applyHasPlayer' => $applyHasPlayer]);
    }

    //向指定档位增加队员
    public function addPlayer(Request $request)
    {
        Log::info($request->apply_id);
        Log::info($request->user_id);
        Log::info($request->user_level);
        $player = ApplyHasPlayer::where('apply_id', '=', $request->apply_id)
                ->where('user_id', '=', $request->user_id)
                ->first();
        if(!empty($player)){
            return $this->message('该队员已经分配');
        }else{
            //新建一个
            $apply_has_player = ApplyHasPlayer::create([
                'apply_id' => $request->apply_id,
                'user_id' => $request->user_id,
                'user_level' => $request->user_level,
            ]);
            $apply_has_player->save();
            return $this->message('分配成功');
        }
        
        //return $this->success(['applyHasPlayer' => $applyHasPlayer]);
    }

    //向指定档位删除队员
    public function delPlayer(Request $request)
    {
        Log::info($request->id);
        $player = ApplyHasPlayer::where('id', '=', $request->id)
                ->first();
        if(empty($player)){
            return $this->message('未找到该队员');
        }else{
            $player->delete();
            return $this->message('删除成功');
        }
    }
    
    //删除最后一个档位的所有队员
    public function delLevel(Request $request)
    {
        Log::info($request->apply_id);
        Log::info($request->level);
        $player = ApplyHasPlayer::where('apply_id', '=', $request->apply_id)
                ->where('user_level', '=', $request->level);
        $player->delete();
        return $this->message('删除成功');
    }

    public function setApply(Request $request, Apply $apply/*, RoleValidate $validate*/)
    {
        Log::info($request->setApplyForm);
        //$apply = Apply::where('id', $request->setApplyForm['id'])->first();
        $apply = $apply->findOrFail($request->setApplyForm['id']);
        if(!empty($apply)){
            $apply->group = $request->setApplyForm['group'];
            $apply->referee = $request->setApplyForm['referee'];
            $apply->round = $request->setApplyForm['round'];
            $apply->referee_level = $request->setApplyForm['referee_level'];
            $apply->save();
        }
        
        /*Log::info($request->players);
        foreach ($request->players as $player) {
            $apply_has_player = ApplyHasPlayer::where('apply_id',$apply->id)
                        ->where('user_id',$player['user_id'])
                        ->first();
            $apply_has_player->user_level = $player['user_level'];
            $apply_has_player->save();
        }*/
        return $this->message('操作成功');
    }

    public function changeStatus(Request $request, Apply $apply/*, RoleValidate $validate*/)
    {
        Log::info('changeStatus--------------------');
        Log::info($request->id);
        Log::info($request->status);
        $apply = $apply->findOrFail($request->id);
        if(!empty($apply)){
            $apply->enable = $request->status;
            $apply->save();
        }
        //判断一下，如果有就不生成，只有第一次没有时生成 todo
        $drawlots = Drawlot::where('apply_id', '=', $apply->id)->get();
        if(!empty($drawlots)){
            return $this->message('操作成功');
        }

        $applyhasplayers = ApplyHasPlayer::where('apply_id', '=', $apply->id)->get();
        Log::info($applyhasplayers);
        if($request->status == 'T'){
            foreach($applyhasplayers as $applyhasplayer){
                Log::info($applyhasplayer->user_id);
                Log::info($applyhasplayer->user_level);
                Log::info($apply->round);
                for($i=1;$i<=$apply->round;$i++){
                    Log::info($i);
                    $drawlot = Drawlot::firstOrNew(['apply_id' => $apply->id, 'user_id' => $applyhasplayer->user_id, "round" => $i]);
                    $drawlot->user_level = $applyhasplayer->user_level;
                    $drawlot->save();
                }
            }
        }
        return $this->message('操作成功');
    }

    public function resetDrawlot(Request $request, Apply $apply)
    {
        Log::info('resetDrawlot--------------------');
        $apply = $apply->findOrFail($request->apply_id);
        Log::info($apply->id);
        Log::info($apply->round);
        Log::info($request->apply_id);

        $drawlots = Drawlot::where('apply_id', '=', $request->apply_id);
        $drawlots->delete();

        $applyhasplayers = ApplyHasPlayer::where('apply_id', '=', $request->apply_id)->get();
        Log::info($applyhasplayers);
        
        foreach($applyhasplayers as $applyhasplayer){
            Log::info($applyhasplayer->user_id);
            Log::info($applyhasplayer->user_level);
            Log::info($apply->round);
            for($i=1;$i<=$apply->round;$i++){
                Log::info($i);
                $drawlot = Drawlot::firstOrNew(['apply_id' => $request->apply_id, 'user_id' => $applyhasplayer->user_id, "round" => $i]);
                $drawlot->user_level = $applyhasplayer->user_level;
                $drawlot->save();
            }
        }
        
        return $this->message('操作成功');
    }
}
